import {
  getcheckroomModalityTypeGroupList,
  getHospList,
  getDepAreaList,
  getDepList,
  getModalityList,
  getCheckRoomList,
  getAppTempList,
  getAppointmentCheckroomRecommendlist,
  getAppTempAppointmentlist,
  getAppLists,
  addAppTemp,
  editAppTemp,
  getCheckroomModel,
  importAppListsbatchupdate,
  getAppointmentparameterdmb,
  getAppointmentparameterdmbgetlist,
  addAppointmentparameterdmb,
  eidtAppointmentparameterdmb,
  postAppTempbatchupdate,
  updateAppLists,
  insertAppLists,
  getBigPartList,
  getHisTree,
  getHisCheckroomgetSmallpartlist,
  postappointmentlistdmbsyncappointment,
  appointmentlistdmbBatchmove,
  gethasappointdmb
} from '@/api/api'
import { getDefaultCheckRoom, getLocalStorageKey } from '@/utils/auth'
import { getLocalStorage } from '@/utils/localStorage' // removeLocalStorage
import { isNull, setRoomKeyToDeptRoom, getDeptRoomByKey, getLocalSetMemory } from '@/utils/utils'
import store from '@/store'

export const depSalt = 'SALT-DEP-'
export const modalitySalt = 'SALT-MODALITY-'
export const modalityTypeSalt = 'SALT-MTYPE-'
export const roomSalt = 'SALT-ROOM-'

// 设置时间，补齐 hh:mm:ss
const setTimeSecond = (time) => {
  let t = time.split(':')
  if (t.length === 2) {
    t.push('00')
  }
  return t.join(':')
}
function isArrayFn(value){
  if (typeof Array.isArray === "function") {
    return Array.isArray(value);
  }else{
    return Object.prototype.toString.call(value) === "[object Array]";
  }
}
/**
 * 机房选择的组件数据
 * @param {*} data Array
 * @param {*} resTree Array
 * @returns resTree
 */
const roomTreeOptions = (data, resTree, isEnd) => {
  if (typeof data === 'object') {
    data.forEach(item => {
      let optionObj = {
        text: '',
        label: '',
        value: ''
      }
      if (typeof item === 'object' && !isEnd) {
        optionObj.children = []
        // if (item.hospitalCode) {
        //   optionObj.text = item.hospitalName
        //   optionObj.label = item.hospitalName
        //   optionObj.value = item.hospitalCode
        //   if (item.depAreaCheckRooms.length > 0) {
        //     roomTreeOptions(item.depAreaCheckRooms, optionObj.children)
        //   }
        // } else
        if (item.depArea) {
          optionObj.text = item.depArea
          optionObj.label = item.depArea
          optionObj.value = item.depArea
          if (item.depCheckRooms.length > 0) {
            // // console.log('item.depCheckRooms', item.depCheckRooms)
            roomTreeOptions(item.depCheckRooms, optionObj.children)
          }
        } else if (item.dep) {
          optionObj.text = item.dep
          optionObj.label = item.dep
          optionObj.value = depSalt+item.dep
          if (item.modalityTypes.length > 0) {
            roomTreeOptions(item.modalityTypes, optionObj.children)
          }
        } else if (item.modalityType) {
          optionObj.text = item.modalityType
          optionObj.label = item.modalityType
          optionObj.value = modalityTypeSalt+item.modalityType
          if (item.modalityCheckRooms.length > 0) {
            roomTreeOptions(item.modalityCheckRooms, optionObj.children, 'isEnd')
          }
        }
        resTree.push(optionObj)
      } else {
        // 机房与设备一起在这里设置
        optionObj.text = item.checkRoom + '$#' + item.modality
        // optionObj.label = item.checkRoom+','+item.modality
        optionObj.label = item.checkRoom
        optionObj.value = item.checkRoom + '$#' + item.modality
        resTree.push(optionObj)
      }
    })
  }
}

function getParamsVal(ps) {
  const p = JSON.parse(JSON.stringify(ps))
  if (typeof p === 'object') {
    for (var k in p) {
      let sk = ''
      switch (k) {
        case 'Dep':
        case 'dep':
          sk = depSalt
          break;
        case 'ModalityType':
        case 'modalityType':
          sk = modalityTypeSalt
          break;
      }
      if (sk) {
        p[k] = p[k] && p[k].indexOf(sk) >= 0 ? p[k].replace(sk, '') : p[k]
      }
      if ((k === 'CheckRoom' || k === 'checkRoom') && p[k]) {
        // 机房值为：机房+设备 ，需要切分
        const cr = p[k].indexOf('$#') > 0 ? p[k].split('$#') : [p[k]]
        p[k] = cr[0]
        if (cr.length > 1) {
          p['Modality'] = cr[1]
        }
      }
      // param.Dep = param.Dep && param.Dep.indexOf(depSalt) >= 0 ? param.Dep.replace(depSalt, '') : param.Dep
      // param.Modality = param.Modality && param.Modality.indexOf(modalityTypeSalt) >= 0 ? param.Modality.replace(modalityTypeSalt, '') : param.Modality
      // param.CheckRoom = param.CheckRoom && param.CheckRoom.indexOf(roomSalt) >= 0 ? param.CheckRoom.replace(roomSalt, '') : param.CheckRoom
    }
  }
  return p
}

export function getHasAppointdmb(p) {
  // gethasappointdmb(p).then(res => {
  //   // console.log('gethasappointdmb=>res', gethasappointdmb)
  // })
  return new Promise(async resolve => {
    // 机房类型 0检查机房、1虚拟机房、2预约池,-1全部
    const vr = getLocalStorage('VirtualRoomKey')
    const params = {
      ...getParamsVal(p)
    }
    await gethasappointdmb(params).then(res => {
      if (res && res.code === 10000 && res.content) {
        const _list = res.content.list
        // console.log('gethasappointdmb=>_list', _list)
        resolve(_list)
      }
      resolve([])
    })
  })
}
function setDeptRoom(roomTree) {
  let defaultArr = []
  let _deparea = roomTree[0]
  let _dep = _deparea.children[0]
  let _modality = _dep.children[0]
  let _room = _modality.children[0]
  defaultArr.push(_deparea.value)
  defaultArr.push(_dep.value)
  defaultArr.push(_modality.value)
  defaultArr.push(_room.value)
  // console.log('setRoomKeyToDeptRoom11111111', defaultArr)
  setRoomKeyToDeptRoom(defaultArr)
}
// 获取机房数据树
export function getCheckroomGroupListTree(hospitalCode) {
  return new Promise(async resolve => {
    // 机房类型 0检查机房、1虚拟机房、2预约池,-1全部
    const vr = getLocalStorage('VirtualRoomKey')
    const params = {
      HospitalCode: hospitalCode,
      VirtualRoom: vr ? vr*1 : -1
    }
    await getcheckroomModalityTypeGroupList(params).then(res => {
      if (res && res.code === 10000 && res.content) {
        const _list = res.content.list
        let roomTree = []
        if (_list.length > 0) {
          roomTreeOptions(_list, roomTree)
        }
        // console.log('roomTree=>getCheckroomGroupListTree', roomTree)
        // 在这里就要和缓存中的yjyy-roomKeyToDeptRoom进行对比了
        // mapkey:['学1院路影像楼', 'SALT-DEP-CT', 'SALT-MTYPE-CT', 'CT1室$#CT']
        // 把院区/影像区域+检查部门+检查设备来进行对比，若不一致，则重新获取
        // if (mapkey[0])
        const mapkey = getDeptRoomByKey()
        const index = roomTree.findIndex(item => item.text == mapkey[0])
        // console.log('index', index)
        if (index > -1) {
          const curMapKey = roomTree[index]
          // console.log('curMapKey', curMapKey)
          const depIndex = curMapKey.children.findIndex(item => item.value == mapkey[1])
          // console.log('depIndex', depIndex)
          if (depIndex > -1) {
            const curMapDep = curMapKey.children[depIndex]
            // console.log('curMapDep', curMapDep)
            const mtypeIndex = curMapDep.children.findIndex(item => item.value == mapkey[2])
            // console.log('mtypeIndex', mtypeIndex)
            if (mtypeIndex == -1) {
              setDeptRoom(roomTree)
            }
          } else {
            setDeptRoom(roomTree)
          }
        } else {
          setDeptRoom(roomTree)
        }
        resolve(roomTree)
      }
      resolve([])
    })
  })
}
// 获取医院列表
export function getHospListPost() {
  return new Promise(async resolve => {
    await getHospList().then(res => {
      if (res && res.code === 10000 && res.content) {
        const _list = res.content.list
        _list.forEach(item => {
          item.value = item.code
          item.label = item.name
        })
        resolve(_list)
      }
      resolve([])
    })
  })
}
// 获取院区列表
export function getDepAreaListPost(hospitalCode) {
  return new Promise(async resolve => {
    const params = {
      HospitalCode: hospitalCode
    }
    await getDepAreaList(params).then(res => {
      if (res && res.code === 10000 && res.content) {
        const _list = res.content.list
        const resList = []
        _list.forEach(item => {
          const obj = {
            value: item,
            label: item
          }
          resList.push(obj)
        })
        resolve(resList)
      }
      resolve([])
    })
  })
}
// 获取部门列表
export function getDepListPost(hospitalCode, depArea) {
  return new Promise(async resolve => {
    const params = {
      HospitalCode: hospitalCode,
      DepArea: depArea
    }
    await getDepList(params).then(res => {
      if (res && res.code === 10000 && res.content) {
        const _list = res.content.list
        const resList = []
        _list.forEach(item => {
          const obj = {
            value: depSalt + item,
            label: item
          }
          resList.push(obj)
        })
        resolve(resList)
      }
      resolve([])
    })
  })
}
// 获取设备列表
export function getModalityListPost(hospitalCode, dep, depArea) {
  const params = {hospitalCode, dep, depArea}
  return new Promise(async resolve => {
    const param = {...getParamsVal(params)}
    await getModalityList(param).then(res => {
      if (res && res.code === 10000 && res.content) {
        const _list = res.content.list
        const resList = []
        _list.forEach(item => {
          const obj = {
            value: modalityTypeSalt + item,
            label: item
          }
          resList.push(obj)
        })
        resolve(resList)
      }
      resolve([])
    })
  })
}
// 获取机房列表
export function getCheckRoomListPost(hospitalCode, dep, depArea, modality) {
  const params = {
    hospitalCode, dep, depArea, modality
  }
  return new Promise(async resolve => {
    const param = {...getParamsVal(params)}
    await getCheckRoomList(param).then(res => {
      if (res && res.code === 10000 && res.content) {
        const _list = res.content.list
        const resList = []
        _list.forEach(item => {
          const obj = {
            value: item,
            label: item,
            leaf: true
          }
          resList.push(obj)
        })
        resolve(resList)
      }
      resolve([])
    })
  })
}

// 获取默认第一条的 (医院/) 院区/部门/科室/机房 数组
export function getDefaultCheckRoomArr(hospitalCode, isNew) {
  let defaultArr = []
  let localRoom = getDefaultCheckRoom()
  // console.warn('localRoom', JSON.stringify(localRoom))
  let localRoomTree = getLocalStorageKey('roomTree')
  let mapkey = getDeptRoomByKey()
  // console.warn('getDefaultCheckRoomArr=>mapkey', mapkey)
  return new Promise(async resolve => {
    if (localRoom && localRoom.length > 0 && !isNew) {
      // 如果本地缓存，存在查询条件数组，直接返回
      resolve({room: localRoom, roomTree: localRoomTree?JSON.parse(localRoomTree):[]})
      return
    }
    const _tree = await getCheckroomGroupListTree(hospitalCode)
    // console.warn('getDefaultCheckRoomArr=>_tree', _tree)
    if (_tree.length>0) {
      // await store.dispatch('user/getDefaultCheckRoomTree', _tree)
      // const _hospIndex = hospitalCode ? _tree.findIndex(item => item.value === hospitalCode) : -1
      // const _hosp = _hospIndex >= 0 ? _tree[_hospIndex] : _tree[0]
      if(!isNull(mapkey)) {
        // console.warn('not isNull mapkey', mapkey)
        // 权限配置的缓存若存在，优先取权限配置中的值
        // let localMomery = getLocalSetMemory()
        // if (localMomery.depArea && localMomery.dep && localMomery.modalitytype) {
        //   let mapKeyFromLM = []
        //   mapKeyFromLM.push(localMomery.depArea)
        //   mapKeyFromLM.push(`SALT-DEP-${localMomery.dep}`)
        //   mapKeyFromLM.push(`SALT-MTYPE-${localMomery.modalitytype}`)
        //   mapkey = mapKeyFromLM
        // }
        defaultArr = mapkey
      } else {
        // console.warn('isNull mapkey')
        let _deparea = _tree[0]
        let _dep = _deparea.children[0]
        let _modality = _dep.children[0]
        let _room = _modality.children[0]
        defaultArr.push(_deparea.value)
        defaultArr.push(_dep.value)
        defaultArr.push(_modality.value)
        defaultArr.push(_room.value)
        // console.log('mapkey', mapkey)
        if (isNull(mapkey)) {
          // console.log('setRoomKeyToDeptRoom222222', defaultArr)
          setRoomKeyToDeptRoom(defaultArr)
        }

        // defaultArr.push(_hosp.value)
        // if (!isNull(_deparea) && !isNull(_dep) && !isNull(_modality) && !isNull(_room)) {
        //   defaultArr.push(_deparea.value)
        //   defaultArr.push(_dep.value)
        //   defaultArr.push(_modality.value)
        //   defaultArr.push(_room.value)
        // }
        // else {
        //   defaultArr.push(isNull(_deparea) ? {} : _deparea.value)
        //   defaultArr.push(isNull(_dep) ? {} : _dep.value)
        //   defaultArr.push(isNull(_modality) ? {} : _modality.value)
        //   defaultArr.push(isNull(_room) ? {} : _room.value)
        // }
      }
      defaultArr.unshift(hospitalCode)
      // console.warn('defaultArr', JSON.stringify(defaultArr))
      // // console.log('__tree', _tree)
      resolve({room: defaultArr, roomTree: _tree})
    } else {
      // await store.dispatch('user/getDefaultCheckRoomTree', [])
      resolve({room: [], roomTree: []})
    }
  })
}

/**
 * 获取机房对象数据，自动排班 api post
 * @param {*} params 接口传参
 * @returns
 */
export function getCheckroomModelAutoPublish(params) {
  // 参数去盐
  const param = { ...getParamsVal(params) }
  // console.warn('getCheckroomModelAutoPublish=>param', param)
  return new Promise(async resolve => {
    await getCheckroomModel(param).then(res => {
      if (res && res.code === 10000) {
        resolve(res.content)
      }
    }).finally(() => {
      // console.log('getCheckroomModelAutoPublish=>param', param)
    })
    resolve([])
  })
}

/**
 * 获取参数模板数据，分页
 * @param {*} params 接口传参
 * @returns
 */
export function getAppointmentParamsPageList(params) {
  // 参数去盐
  const param = { ...getParamsVal(params) }
  return new Promise(async resolve => {
    await getAppointmentparameterdmb(param).then(res => {
      if (res && res.code === 10000) {
        // // // console.log('getAppointmentparameterdmb:===', res.content)
        resolve(res)
      }
    })
    resolve([])
  })
}
/**
 * 获取参数模板数据，不分页
 * @param {*} params 接口传参
 * @returns
 */
export function getAppointmentParamsTempList(params) {
  // 参数去盐
  const param = { ...getParamsVal(params) }
  return new Promise(async resolve => {
    await getAppointmentparameterdmbgetlist(param).then(res => {
      if (res && res.code === 10000) {
        // // // console.log('getAppointmentparameterdmb:===', res.content)
        resolve(res)
      }
    })
    resolve([])
  })
}
/**
 * 新增参数模板
 * @param {*} params 接口传参
 * @returns
 */
export function addAppointmentParamsTemp(params) {
  // 参数去盐
  const param = { ...getParamsVal(params) }
  return new Promise(async resolve => {
    await addAppointmentparameterdmb(param).then(res => {
      if (res && res.code === 10000) {
        // // // console.log('getAppointmentparameterdmb:===', res.content)
        resolve(res)
      }
    })
    resolve([])
  })
}
/**
 * 修改参数模板
 * @param {*} params 接口传参
 * @returns
 */
export function eidtAppointmentParamsTemp(params) {
  // 参数去盐
  const param = { ...getParamsVal(params) }
  return new Promise(async resolve => {
    await eidtAppointmentparameterdmb(param).then(res => {
      if (res && res.code === 10000) {
        // // // console.log('getAppointmentparameterdmb:===', res.content)
        resolve(res)
      }
    })
    resolve([])
  })
}

/**
 * 获取预约时段排班数据 api post
 * @param {*} params 接口传参
 * @returns 接口返回当前时间段排班数据
 */
export function getAppointmentList(params) {
  // 参数去盐
  const param = { ...getParamsVal(params) }
  // // // console.log('getAppointment:====', param)
  return new Promise(async resolve => {
    // console.log('let me ses see see:', param)
    await getAppLists(param).then(res => {
      if (res && res.code === 10000) {
        // // console.log('getAppLists', res.content.list)
        /*
        res.content.list.forEach((item, index) => {
          if(index == 30 || index == 40) {
            item.checkNum = -5
            item.callNum = 5
          }
          if(index == 32) {
            item.callNum = 15
          }
        })
        * */
        // // // console.log('getAppointmentList1:===', res.content.list)
        resolve(res.content.list)
      }
    })
    resolve([])
  })
}
/**
 * 获取预约时段排班模板数据 api post
 * @param {*} params 接口传参
 * @returns 接口返回当前时间段排班数据
 */
export function getAppTempAppointmentlistRoom(params) {
  // 参数去盐
  const param = { ...getParamsVal(params) }
  return new Promise(async resolve => {
    await getAppTempAppointmentlist(param).then(res => {
      if (res && res.code === 10000) {
        // // // console.log('TempList-res:===', res.content.list)
        resolve(res.content.list)
      }
    })
    resolve([])
  })
}
/**
 * 获取预约时段排班模板数据，历史对比 api post
 * @param {*} params 接口传参
 * @returns 接口返回当前时间段排班数据
 */
export function getAppointmentTempRecommendList(params) {
  const param = {
    // 参数去盐
    ...getParamsVal(params),
    IsHasFilters: true
  }
  return new Promise(async resolve => {
    await getAppointmentCheckroomRecommendlist(param).then(res => {
      if (res && res.code === 10000) {
        // // // console.log('TempList-res:===', res.content.list)
        resolve(res.content.list.map(item => { return {...item, recommendflag: true} }))
      }
    })
    resolve([])
  })
}
/**
 * 获取预约时段排班模板数据 api post
 * @param {*} params 接口传参
 * @returns 接口返回当前时间段排班数据
 */
export function getAppointmentTempList(params) {
  const param = {
    // 参数去盐
    ...getParamsVal(params),
    IsHasFilters: true
  }
  return new Promise(async resolve => {
    await getAppTempList(param).then(res => {
      if (res && res.code === 10000) {
        // // console.log('TempList-res:===', res.content.list)
        resolve(res.content.list)
      }
    })
    resolve([])
  })
}
/**
 * 批量覆盖，预约时段排班模板数据
 * @param {*} params 接口传参
 * @returns
 */
export function postAppTempbatchupdateSend(params, isUpdateBtn) {
  // 参数去盐
  // alert(isUpdateBtn)
  let param = { ...getParamsVal(params) }
  let newArr = [], appointmentFilters = [], appointmentFiltersItem = {}
  param.batchUpdateAppointmentCheckRoomDmbs.forEach(item => {
    item.beginTime = setTimeSecond(item.beginTime)
    item.endTime = setTimeSecond(item.endTime)
    // newArr.push(item)
    if (isUpdateBtn) {
      if (item.recordCode) {
        item.initialNum = Number(item.initialNum)
        appointmentFilters = item.appointmentFilters.filter(item2 => item2.parametersName)
        // // // console.log('appointmentFilters', appointmentFilters)
        item.appointmentFilters = appointmentFilters
        newArr.push(item)
      }
    }
  })
  if (isUpdateBtn) {
    param.batchUpdateAppointmentCheckRoomDmbs = newArr
  }
  return new Promise(async resolve => {
    await postAppTempbatchupdate(param).then(res => {
      if (res && res.code === 10000) {
        resolve(res)
      }
    })
    resolve([])
  })
}
/**
 * 批量更新，指定日期后的模板数据
 * @param {*} params 接口传参
 * @returns
 */
 export function postappointmentlistdmbsyncappointmentSend(params) {
   // 参数去盐
  const param = { ...getParamsVal(params) }
  param.syncAppointmentCheckRoomDmbs.forEach(item => {
    item.beginTime = setTimeSecond(item.beginTime)
    item.endTime = setTimeSecond(item.endTime)
  })

  return new Promise(async resolve => {
    await postappointmentlistdmbsyncappointment(param).then(res => {
      if (res && res.code === 10000) {
        resolve(res)
      }
    })
    resolve([])
  })
}
/**
 * 新增预约时段排班模板数据 api post
 * @param {*} params 接口传参
 * @returns
 */
export function addAppTempSend(params) {
  // 参数去盐
  const param = { ...getParamsVal(params) }
  param.beginTime = setTimeSecond(param.beginTime)
  param.endTime = setTimeSecond(param.endTime)
  return new Promise(async resolve => {
    await addAppTemp(param).then(res => {
      if (res && res.code === 10000) {
        resolve(res)
      }
    })
    resolve([])
  })
}
/**
 * 修改预约时段排班模板数据 api
 * @param {*} params 接口传参
 * @returns
 */
export function editAppTempSend(params) {
  // 参数去盐
  const param = { ...getParamsVal(params) }
  param.beginTime = setTimeSecond(param.beginTime)
  param.endTime = setTimeSecond(param.endTime)
  return new Promise(async resolve => {
    await editAppTemp(param).then(res => {
      if (res && res.code === 10000) {
        resolve(res)
      }
    })
    resolve([])
  })
}
/**
 * 号源迁移 appointmentlistdmbBatchmove
 */
export function appointmentlistdmbBatchmoveSend(params) {
   // 参数去盐
  const param = { ...getParamsVal(params) }
  return new Promise(async resolve => {
    await appointmentlistdmbBatchmove(param).then(res => {
      if (res && res.code === 10000) {
        resolve(res)
      }
    })
    resolve([])
  })
}

/**
 * 批量修改，预约时段排班数据
 * @param {*} params 接口传参
 * @returns
 */
 export function importAppListsbatchupdateSend(params) {
   // 参数去盐
  const param = { ...getParamsVal(params) }
  param.batchUpdateAppointmentListDmbs.forEach(item => {
    item.beginTime = setTimeSecond(item.beginTime)
    item.endTime = setTimeSecond(item.endTime)
  })

  return new Promise(async resolve => {
    await importAppListsbatchupdate(param).then(res => {
      if (res && res.code === 10000) {
        resolve(res)
      }
    })
    resolve([])
  })
}
/**
 * 修改，预约时段排班数据
 * @param {*} params 接口传参
 * @returns
 */
 export function updateAppListsSend(params) {
   // 参数去盐
  const param = { ...getParamsVal(params) }
  param.beginTime = setTimeSecond(param.beginTime)
  param.endTime = setTimeSecond(param.endTime)
  return new Promise(async resolve => {
    await updateAppLists(param).then(res => {
      if (res && res.code === 10000) {
        resolve(res)
      }
    })
    resolve([])
  })
}
/**
 * 新增，预约时段排班数据
 * @param {*} params 接口传参
 * @returns
 */
 export function insertAppListsSend(params) {
   // 参数去盐
  const param = { ...getParamsVal(params) }
  param.beginTime = setTimeSecond(param.beginTime)
  param.endTime = setTimeSecond(param.endTime)
  return new Promise(async resolve => {
    await insertAppLists(param).then(res => {
      if (res && res.code === 10000) {
        resolve(res)
      }
    })
    resolve([])
  })
}
/**
 * 修改，或新增 排班预约数据
 * @param {*} appoInfo 提交的排班预约数据
 * @param {*} isAdd 判断是否新增，false 修改
 * @returns
 */
export const popSendType = (appoInfo, isAdd) => {
  return new Promise(async resolve => {
    if (isAdd) {
      const appoRes = await insertAppListsSend(appoInfo)
      resolve(appoRes)
    } else {
      const appoRes = await updateAppListsSend(appoInfo)
      resolve(appoRes)
    }
  })
}
/**
 * 排班预约时段修改
 * @param {*} updateAppoReqs 请求任务数组
 * @param {*} limit 并发数
 * @returns
 */
export function updateOrInsertAppoListsSendPop(updateAppoReqs, isAdd, limit = 3) {
  // limit 是并发数，一个数组的长度
  return new Promise((resolve, reject) => {
    const len = updateAppoReqs.length
    let counter = 0
    let taskIsStop = false
    if (len === 0) {
      resolve(counter)
      return
    }
    // 开始执行任务函数
    const start = async () => {
      // 停止并发任务
      if(taskIsStop) {
        resolve(counter)
      }
      const task = updateAppoReqs.shift()
      if (task) {
        try {
          const appoRes = await popSendType(task, isAdd)
          if(!taskIsStop && appoRes){
            if(counter === len - 1) {
              // 任务执行完成
              resolve(counter)
            }else{
              counter++
              // 启动执行下一个任务
              start()
            }
          }else{
            taskIsStop = true
            resolve(counter)
          }
        } catch (err) {
          // 请求报错
          // 判断报错次数
          if(task.error < 3) {
            // 报错累加
            task.error++
            // 把当前报错任务放到任务数组前段，下次直接执行任务
            updateAppoReqs.unshift(task)
            start()
          }
        }
      }
    }
    // 开始执行并发任务
    while(limit > 0) {
      start()
      limit -= 1
    }
  })
}

/**
 * 获取部位
 * @param {*} params 接口传参
 * @returns
 */
 export function getBigPartListRoom(params) {
   // 参数去盐
  const param = { ...getParamsVal(params) }
  return new Promise(async resolve => {
    await getBigPartList(param).then(res => {
      if (res && res.code === 10000) {
        resolve(res)
      }
    })
    resolve([])
  })
}
/**
 * 获取检查部位、检查项目树 tree
 * @param {*} params 接口传参
 * @returns
 */
 export function getBigPartGettreeRoom(params) {
   // 参数去盐
  const param = { ...getParamsVal(params) }
  return new Promise(async resolve => {
    await getHisTree(param).then(res => {
      if (res && res.code === 10000) {
        resolve(res)
      }
    })
    resolve([])
  })
}
/**
 * 获取检查项目（小部位）
 * @param {*} params 接口传参
 * @returns
 */
 export function getHisCheckroomgetSmallpartlistRoom(params) {
   // 参数去盐
  const param = { ...getParamsVal(params) }
  return new Promise(async resolve => {
    await getHisCheckroomgetSmallpartlist(param).then(res => {
      if (res && res.code === 10000) {
        resolve(res)
      }
    })
    resolve([])
  })
}
